<template>
  <div v-loading="loading">
    <el-row :gutter="10">
      <el-col
        :span="24"
        style="text-align: left"
      >
        <div style="display: flex">
          <el-button
            type=""
            @click="buttonClicks.inputBtnClick"
            v-show="false"
          >
            <el-icon
              :size="20"
              color="#67C23A"
            >
              <Bottom />
            </el-icon>
            订单接入
          </el-button>
          <el-button
            type=""
            @click="buttonClicks.xiaDaBtnClick"
            v-show="[0].includes(tableDatas.filters.state)"
          >
            <el-icon
              :size="20"
              color="#67C23A"
            >
              <Bottom />
            </el-icon>
            下达
          </el-button>
          <el-button
            type=""
            @click="buttonClicks.quXiaoXiaDaBtnClick"
            v-show="[10].includes(tableDatas.filters.state)"
          >
            <el-icon
              :size="20"
              color="#67C23A"
            >
              <Top />
            </el-icon>
            取消下达
          </el-button>
          <!-- <el-button
            type=""
            @click="buttonClicks.addBtnClick"
            v-show="[10].includes(tableDatas.filters.state)"
          >
            <el-icon
              :size="20"
              color="#67C23A"
            >
              <Right />
            </el-icon>
            预排产
          </el-button> -->
          <!-- <el-button
            type=""
            @click="buttonClicks.addBtnClick"
          >
            <el-icon
              :size="20"
              color="#67C23A"
            >
              <Back />
            </el-icon>
            撤销预排产
          </el-button> -->
          <!-- <el-button
            type=""
            @click="buttonClicks.addBtnClick"
          >
            <el-icon
              :size="20"
              color="#E6A23C"
            >
              <Remove />
            </el-icon>
            终止
          </el-button> -->
          <el-button
            type=""
            @click="buttonClicks.deleteBtnClick"
            v-show="[0,10,11,2].includes(tableDatas.filters.state)"
          >
            <el-icon
              :size="20"
              color="#F56C6C"
            >
              <Delete />
            </el-icon>
            删除
          </el-button>
          <el-button
            type=""
            @click="buttonClicks.refreshBtnClick"
          >
            <el-icon
              :size="20"
              color="#67C23A"
            >
              <Refresh />
            </el-icon>
            刷新
          </el-button>
          <div style="width: 240px;margin-left: 10px;">

            <el-date-picker
              v-model="tableDatas.filters.dateRange"
              type="daterange"
              range-separator="到"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 90%;"
            />
          </div>

          <el-button
            style="margin-left: 5px;"
            @click="buttonClicks.finishBtnClick"
            v-show="[0,10].includes(tableDatas.filters.state)"
          >
            <el-icon
              :size="20"
              color="#67C23A"
            >
              <Check />
            </el-icon>
            确认完成
          </el-button>
          <el-input
            v-model="tableDatas.filters.searchText"
            clearable
            style="width: 400px;margin-left: 10px;"
          >
            <template #prepend>
              <el-icon style="font-weight: bold;">
                <Search />
              </el-icon>
              搜索
            </template>
          </el-input>
        </div>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.title"
      top="5vh"
      width="80vw"
    >
      <el-scrollbar max-height="70vh">
        <el-tabs model-value="生产订单">
          <el-tab-pane
            label="生产订单"
            name="生产订单"
          >
            <ProductionOrderInfo :workorder="dialogDatas.orderData.workorder"></ProductionOrderInfo>
          </el-tab-pane>
          <el-tab-pane
            label="工艺配置"
            name="工艺配置"
          >
            <ProductionProcessInfo
              :process-list="dialogDatas.orderData.processData.tableData"
              @add-process="dialogDatas.orderData.processData.handleAdd"
              @delete-process="dialogDatas.orderData.processData.handleDelete"
              @replace-process="dialogDatas.orderData.processData.handleReplace"
            ></ProductionProcessInfo>
          </el-tab-pane>
          <el-tab-pane
            label="Bom"
            name="Bom"
          >
            <ProductionBomInfo
              :work-order-id="dialogDatas.orderData.orderId"
              :bom-data="dialogDatas.orderData.bomData.tableData"
            >

            </ProductionBomInfo>
          </el-tab-pane>
          <el-tab-pane
            label="SN清单"
            name="SN清单"
          >
            <production-sn-info
              :work-order-id="dialogDatas.orderData.orderId"
              :sn-data="dialogDatas.orderData.snData.tableData"
            >
            </production-sn-info>
          </el-tab-pane>
          <!-- <el-tab-pane
            label="MES标准工序"
            name="MES标准工序"
          >Task</el-tab-pane> -->
        </el-tabs>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表格右键菜单 -->
    <teleport to="body">
      <el-dropdown
        ref="dropdown"
        v-model="tableDatas.filters.contextMenu.visible"
        :hide-on-click="true"
        trigger="contextmenu"
      >
        <div :style="{ 
            left: tableDatas.filters.contextMenu.left + 'px',
            top: tableDatas.filters.contextMenu.top + 'px',
            position: 'fixed',
          }">
        </div>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="tableDatas.handleMenuClick('查看详情')">查看详情</el-dropdown-item>
            <el-dropdown-item
              @click="tableDatas.handleMenuClick('删除')"
              divided
            >删除</el-dropdown-item>
            <el-dropdown-item @click="tableDatas.handleMenuClick('复制')">复制</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </teleport>

    <el-row :gutter="10">
      <!-- 状态选择 -->
      <el-col :span="3">
        <el-card
          class="marginTop10"
          shadow="never"
        >
          <el-scrollbar max-height="85vh">
            <div
              v-for="option in tableDatas.filters.stateOptions"
              style="text-align: left"
            >
              <el-radio
                v-model="tableDatas.filters.state"
                :value="option['value']"
                size="large"
                @change="getTableDatas"
              >{{option['label']}}</el-radio>
            </div>
          </el-scrollbar>

        </el-card>
      </el-col>
      <!-- 订单展示 -->
      <el-col :span="21">
        <el-auto-resizer style="height: 90vh;width: 100%">
          <template #default="{ height, width }">

            <el-table-v2
              class="bordered-table marginTop10"
              :data="tableDatas.tableDatasAfterPage"
              :columns="tableDatas.virtualTableColumns"
              :width="width"
              :height="height"
              fixed
              :row-event-handlers="{onContextmenu:tableDatas.handleVirtualContextMenu}"
              :row-class="tableDatas.tableRowClassName"
            >
              <!-- 自定义单元格渲染 -->
              <template #cell="{ column, rowData, rowIndex }">
                <template v-if="column.key === 'checked'">
                  <el-checkbox v-model="rowData.checked" />
                </template>
                <template v-else-if="column.key === 'operate'">
                  <div>
                    <el-button
                      type="success"
                      @click="tableDatas.editBtnClick(rowData)"
                    >修改</el-button>
                    <el-popconfirm
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                      title="确定删除该条记录?"
                      @confirm="tableDatas.deleteBtnClick(rowData)"
                    >
                      <template #reference>
                        <el-button type="danger">删除</el-button>
                      </template>
                    </el-popconfirm>
                  </div>
                </template>
                <template v-else-if="['WOPLANDATE', 'WOCOMDATE', 'CREATETIME'].includes(column.key)">
                  {{ rowData[column.key]?.substring(0, 10) || rowData[column.key] }}
                </template>
                <template v-else>
                  {{ rowData[column.key] }}
                </template>
              </template>
            </el-table-v2>
          </template>
        </el-auto-resizer>

        <!-- <el-table
          class="marginTop10"
          :data="tableDatas.tableDatasAfterPage"
          @row-contextmenu="tableDatas.handleContextMenu"
          :row-class-name="tableDatas.tableRowClassName"
          border
          max-height="88vh"
          empty-text="无数据"
        >
          <el-table-column
            v-for="column in tableDatas.tableColumns"
            :type="column.type"
            :prop="column.prop"
            :label="column.label"
            :align="column.align"
            :formatter="column.formatter"
            :width="column.width"
          >

            <template
              #default="scope"
              v-if="column.prop =='checked'"
            >
              <div>
                <el-checkbox v-model="scope.row.checked" />
              </div>
            </template>

            <template
              #default="scope"
              v-if="column.prop =='operate'"
            >
              <div>
                <el-button
                  type="success"
                  @click="tableDatas.editBtnClick(scope.row)"
                >修改</el-button>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  title="确定删除该条记录?"
                  @confirm="tableDatas.deleteBtnClick(scope.row)"
                >
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table> -->

      </el-col>
    </el-row>

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { nextTick, onMounted, watch } from '@vue/runtime-core';
import { v4 } from 'uuid';
import myAxios from '@/myAxios/myAxios';
import { showSuccess, showWarning } from '@/hooks/useMyMessageBox';
// 图标
import { Search, Bottom, Top, Right, Back, Remove, Delete, Refresh, Calendar, Check } from '@element-plus/icons-vue';
import ProductionOrderInfo from '@/components/ProductionOrderInfo.vue';
import ProductionProcessInfo from '@/components/ProductionProcessInfo.vue';
import ProductionBomInfo from '@/components/ProductionBomInfo.vue';
import { dayjs } from 'element-plus';

export default {
  name: '',
  components: {
    ProductionOrderInfo: ProductionOrderInfo,
    ProductionProcessInfo: ProductionProcessInfo,
    ProductionBomInfo: ProductionBomInfo,
    Search: Search,
    Bottom: Bottom,
    Top: Top,
    Right: Right,
    Back: Back,
    Remove: Remove,
    Delete: Delete,
    Refresh: Refresh,
    Calendar: Calendar,
    Check: Check,
  },
  setup () {
    let loading = ref(false);
    let addBtnClick = function () {
      showFormDialog();
    };
    let inputBtnClick = async function () {
      // 补齐12位工单号
      let order = `50159141`.padStart(12, '0');
      let orderInfoList = await myAxios.getSap('SAP导入SAP生产订单', `${order}`, 9900);
      console.log('orderInfoList :>> ', orderInfoList);
    };
    let xiaDaBtnClick = async function () {
      try {
        loading.value = true;
        let selectData = tableDatas.oritableData.filter(el => el.checked);
        let errorMsg = '';
        if (selectData.length === 0) {
          throw new Error(`请选择要下达的订单！`);
        }
        else {
          for (let i = 0; i < selectData.length; i++) {
            let row = selectData[i];
            let JM_WORKORDERID = row.JM_WORKORDERID;
            let orderParam = `JM_WORKORDER🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
            let orderInfoList = await myAxios.get('陈帅廷查询大连通用数据', `${orderParam}`);
            console.log('orderInfoList :>> ', orderInfoList);
            if (orderInfoList.length === 0) {
              throw new Error(`订单不存在!`);
            }
            else {
              let orderEntity = orderInfoList[0];
              let checkResult = await checkOrderBeforeXiaDa(orderEntity, row);
              if (checkResult.includes('成功')) {

                // 查询序列号数据
                let snList = await myAxios.get('陈帅廷查询大连订单SN使用状态', `${JM_WORKORDERID}`, `9900`);
                // 查询工艺路线数据
                let routeParam = `JM_ORDERROUTE🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
                let routeList = await myAxios.get('陈帅廷查询大连通用数据', `${routeParam}`);

                // 查询BOM列表
                let bomListParam = `JM_WOBOM🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
                let bomList = await myAxios.get('陈帅廷查询大连通用数据', bomListParam);

                // 查询领料列表
                let appListParam = `MATERIALAPPLYFORSN🈹ORDERNO🈹${JM_WORKORDERID}`;
                let appList = await myAxios.get('陈帅廷查询大连通用数据', appListParam);

                //#region 插入 JM_WORKORDERSNRECORD

                let insert_result_JM_WORKORDERSNRECORD = await insert_JM_WORKORDERSNRECORD(snList, routeList);
                console.log('insert_result_JM_WORKORDERSNRECORD :>> ', insert_result_JM_WORKORDERSNRECORD);

                //#endregion

                //#region 插入订单表 MATERIALAPPLYFORSN

                let insert_result_MATERIALAPPLYFORSN = await insert_MATERIALAPPLYFORSN(row, bomList, appList, routeList, snList);
                console.log('insert_result_MATERIALAPPLYFORSN :>> ', insert_result_MATERIALAPPLYFORSN);

                //#endregion

                //#region 更新订单状态 JM_WORKORDER

                let update_result_JM_WORKORDER_STATE = await myAxios.post('MES订单状态调整', `${JM_WORKORDERID}🈹${1}`, '9900');
                console.log('update_result_JM_WORKORDER_STATE :>> ', update_result_JM_WORKORDER_STATE);

                //#endregion

                //#region 移除元素

                let removeIndex = tableDatas.oritableData.indexOf(row);
                tableDatas.oritableData.splice(removeIndex, 1);

                //#endregion
              }
              else {
                throw new Error(checkResult);
              }
            }
          }

          loading.value = false;
          showSuccess('下达成功');
        }
      }
      catch (error) {
        loading.value = false;
        showWarning(error.message);
      }

    };

    let quXiaoXiaDaBtnClick = async function () {
      try {
        loading.value = true;
        let selectData = tableDatas.oritableData.filter(el => el.checked);
        let errorMsg = '';
        if (selectData.length === 0) {
          throw new Error(`请选择要取消下达的订单！`);
        }
        else {
          for (let i = 0; i < selectData.length; i++) {
            let row = selectData[i];
            let JM_WORKORDERID = row.JM_WORKORDERID;
            let orderParam = `JM_WORKORDER🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
            let orderInfoList = await myAxios.get('陈帅廷查询大连通用数据', `${orderParam}`);
            console.log('orderInfoList :>> ', orderInfoList);
            if (orderInfoList.length === 0) {
              throw new Error(`订单不存在!`);
            }
            else {
              let orderEntity = orderInfoList[0];
              let checkResult = await checkOrderBeforeQuXiaoXiaDa(orderEntity, row);
              if (checkResult.includes('成功')) {

                //#region 删除 JM_WORKORDERSNRECORD

                let delete_param_JM_WORKORDERSNRECORD = `JM_WORKORDERSNRECORD🈹DATA1🈹${JM_WORKORDERID}`;
                let delete_result_JM_WORKORDERSNRECORD = await myAxios.post('陈帅廷删除大连通用数据', delete_param_JM_WORKORDERSNRECORD);
                console.log('delete_result_JM_WORKORDERSNRECORD :>> ', delete_result_JM_WORKORDERSNRECORD);

                //#endregion

                //#region 删除 MATERIALAPPLYFORSN

                let delete_param_MATERIALAPPLYFORSN = `MATERIALAPPLYFORSN🈹ORDERNO🈹${JM_WORKORDERID}`;
                let delete_result_MATERIALAPPLYFORSN = await myAxios.post('陈帅廷删除大连通用数据', delete_param_MATERIALAPPLYFORSN);
                console.log('delete_result_MATERIALAPPLYFORSN :>> ', delete_result_MATERIALAPPLYFORSN);

                //#endregion

                //#region 更新订单状态 JM_WORKORDER

                let update_result_JM_WORKORDER_STATE = await myAxios.post('MES订单状态调整', `${JM_WORKORDERID}🈹${0}`, '9900');
                console.log('update_result_JM_WORKORDER_STATE :>> ', update_result_JM_WORKORDER_STATE);

                //#endregion

                //#region 移除元素

                let removeIndex = tableDatas.oritableData.indexOf(row);
                tableDatas.oritableData.splice(removeIndex, 1);

                //#endregion
              }
              else {
                throw new Error(checkResult);
              }
            }
          }

          loading.value = false;
          showSuccess('取消下达成功');
        }
      }
      catch (error) {
        loading.value = false;
        showWarning(error.message);
      }

    };
    let deleteBtnClick = async function () {
      try {
        loading.value = true;
        let selectData = tableDatas.oritableData.filter(el => el.checked);
        let errorMsg = '';
        if (selectData.length === 0) {
          throw new Error(`请选择要删除的订单！`);
        }
        else {
          ElMessageBox.confirm(
            '确定删除生产订单吗？该操作是不可逆的?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(async () => {
            for (let i = 0; i < selectData.length; i++) {
              let row = selectData[i];
              let JM_WORKORDERID = row.JM_WORKORDERID;
              let orderParam = `JM_WORKORDER🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
              let orderInfoList = await myAxios.get('陈帅廷查询大连通用数据', orderParam);
              console.log('orderInfoList :>> ', orderInfoList);
              if (orderInfoList.length === 0) {
                throw new Error(`订单不存在!`);
              }
              else {
                let orderEntity = orderInfoList[0];
                let checkResult = await checkOrderBeforeDelete(orderEntity);
                if (checkResult.includes('成功')) {
                  //更新订单状态
                  let result = await myAxios.post('陈帅廷更新订单状态', `${JM_WORKORDERID}🈹${2}`, '9900');
                  if (result.includes(`成功`)) {
                    let index = tableDatas.oritableData.indexOf(row);
                    tableDatas.oritableData.splice(index, 1);
                  }
                  else {
                    throw new Error(result);
                  }
                }
                else {
                  throw new Error(checkResult);
                }
              }
            }

            loading.value = false;
            showSuccess('删除成功');
          }).catch((error) => {
            if (error.message) {
              loading.value = false;
              showWarning(error.message);
            }
            else if (error == 'cancel') {
              loading.value = false;
            }
            else {
              showWarning(error);
            }
          });
        }
      }
      catch (error) {
        loading.value = false;
        showWarning(error.message);
      }
    };

    let refreshBtnClick = function () {
      getTableDatas();
    };

    let finishBtnClick = function () {

      try {
        loading.value = true;
        let selectData = tableDatas.oritableData.filter(el => el.checked);
        let errorMsg = '';
        if (selectData.length === 0) {
          throw new Error(`请选择要完成的订单！`);
        }
        else {
          ElMessageBox.confirm(
            '确定完成生产订单吗？该操作是不可逆的?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(async () => {
            for (let i = 0; i < selectData.length; i++) {
              let row = selectData[i];
              let JM_WORKORDERID = row.JM_WORKORDERID;
              let orderParam = `${JM_WORKORDERID}🈹${`3`}`;
              let updateResult = await myAxios.post('MES订单状态调整', orderParam);
              if (!updateResult.includes(`成功`)) {
                throw new Error(`订单不存在!`);
              }
              else {
                let index = tableDatas.oritableData.indexOf(row);
                tableDatas.oritableData.splice(index, 1);
              }
            }
            loading.value = false;
            showSuccess('订单完成操作成功!');
          }).catch((error) => {
            if (error.message) {
              loading.value = false;
              showWarning(error.message);
            }
            else if (error == 'cancel') {
              loading.value = false;
            }
            else {
              showWarning(error);
            }
          });
        }
      }
      catch (error) {
        loading.value = false;
        showWarning(error.message);
      }
    };

    //#region 检查函数
    /// 检查订单是否可以取消下达
    let checkOrderBeforeQuXiaoXiaDa = function (orderEntity, row) {
      return new Promise(async (resolve, reject) => {
        let JM_WORKORDERID = orderEntity.JM_WORKORDERID;
        try {
          // 检查订单
          if (orderEntity.WOSTATE != 1) {
            throw new Error("不是排产状态");
          }
          if (orderEntity.WOPLANQTY <= 0) {
            throw new Error("计划数量应当大于0");
          }
          // 检查领料状态
          let lldParam = `MATERIALAPPLYFORSN🈹ORDERNO🈹${JM_WORKORDERID}`;
          let lldInfoList = await myAxios.get('陈帅廷查询大连通用数据', `${lldParam}`);
          if (lldInfoList.filter(p => p.STATE == 1).length > 0) {
            throw new Error("订单已领料,无法取消排产");
          }

          resolve(`订单 ${JM_WORKORDERID} 取消下达检查成功,可以下达`);
        }
        catch (err) {
          resolve(`订单 ${JM_WORKORDERID} ` + err.message);
        }
      });

    };
    /// 检查订单是否可以下达
    let checkOrderBeforeXiaDa = function (orderEntity, row) {
      return new Promise(async (resolve, reject) => {
        let JM_WORKORDERID = orderEntity.JM_WORKORDERID;
        try {
          // 检查订单
          if (orderEntity.WOSTATE != 0) {
            throw new Error("不是新建状态");
          }
          if (orderEntity.WOPLANQTY <= 0) {
            throw new Error("计划数量应当大于0");
          }
          // 检查工艺
          let gyParam = `JM_ORDERROUTE🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
          let gyInfoList = await myAxios.get('陈帅廷查询大连通用数据', `${gyParam}`);
          // let gyInfoList = await myAxios.get('陈帅廷查询大连订单工艺信息', `${JM_WORKORDERID}`);
          if (gyInfoList.filter(p => p.WORKTYPE == 0).length <= 0) {
            throw new Error("没有要采集的订单工序,请配置");
          }
          for (let j = 0; j < gyInfoList.length; j++) {
            let orderRouteEntity = gyInfoList[j];

            if (orderRouteEntity.OUTWORKTAG == 0) {
              if (orderRouteEntity.AVERAGEWORKTIME <= 0) {
                throw new Error("订单工序的平均工时应当大于0");
              }
            }
          }
          // 检查BOM
          let bomParam = `JM_WOBOM🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
          let bomInfoList = await myAxios.get('陈帅廷查询大连通用数据', `${bomParam}`);
          // let bomInfoList = await myAxios.get('陈帅廷查询大连订单BOM信息', `${JM_WORKORDERID}`, '9900');
          for (let j = 0; j < bomInfoList.length; j++) {
            let orderBom = bomInfoList[j];
            if (!orderBom.WOSHOP) {
              throw new Error("Bom需要配置对应的车间");
            }
            if (!orderBom.WOROUTE) {
              throw new Error("Bom需要配置对应的工序");
            }
            if (orderBom.BOMDOSAGE <= 0) {
              throw new Error("BOM单台配置数量要大于0");
            }
            if (!orderBom.WOROUTE) {
              return;
            }
            if (gyInfoList.filter(p => p.JM_ORDERROUTEID == orderBom.WOROUTE).length == 0) {
              throw new Error("BOM的工序不在订单工艺中");
            }

          }
          // 检查流水号
          let snInfoList = await myAxios.get('陈帅廷查询大连订单SN使用状态', `${JM_WORKORDERID}`, `9900`);
          if (orderEntity.WOPLANQTY != snInfoList.length) {
            throw new Error("SN号不足");
          }
          for (let j = 0; j < snInfoList.length; j++) {
            let snItem = snInfoList[j];
            let prosn = snItem.PROSN;
            let snRepeatParam = `JM_WORKORDERSN🈹PROSN🈹${prosn}`;
            let snRepeatData = await myAxios.get('陈帅廷查询大连通用数据', `${snRepeatParam}`);
            // let snRepeatData = await myAxios.get('陈帅廷查询大连订单流水号信息', `${prosn}`, `9900`);
            if (snRepeatData.length > 1) {
              throw new Error("流水号 " + prosn + " 重复");
            }
          }

          resolve(`订单 ${JM_WORKORDERID} 下达检查成功,可以下达`);
        }
        catch (err) {
          resolve(`订单 ${JM_WORKORDERID} ` + err.message);
        }
      });

    };
    /// 检查订单是否可以删除
    let checkOrderBeforeDelete = function (orderEntity) {
      return new Promise(async (resolve, reject) => {
        let JM_WORKORDERID = orderEntity.JM_WORKORDERID;
        try {
          //#region  检查转子
          // 根据订单找到不是新建状态的调度 0-新建，1-开始，2-暂停，3-完工,4删除
          let ddParam = `${JM_WORKORDERID}🈹${`1\',\'2\',\'3\',\'4`}`;
          let ddInfoList = await myAxios.get('陈帅廷查询大连订单调度信息', `${ddParam}`);
          //查找调度下SN，看是否有转子，如果有转子，则不让删除
          for (let i = 0; i < ddInfoList.length; i++) {
            let zzParam = `JM_JOBBATCHNO🈹JM_JOBDISPATCHID🈹${ddInfoList[i]['JM_JOBDISPATCHID']}`;
            let result = await myAxios.get('陈帅廷查询大连通用数据', `${zzParam}`);
            if (result.filter(el => el.PROSN.startsWith('Z')).length > 0) {
              throw new Error("转子调度已经下达，不能删除");
            }
          }
          //#endregion

          //#region 检查领料单
          let lldParam = `MATERIALAPPLYFORSN🈹ORDERNO🈹${JM_WORKORDERID}`;
          let lldInfoList = await myAxios.get('陈帅廷查询大连通用数据', `${lldParam}`);
          // let lldInfoList = await myAxios.get('陈帅廷查询大连订单配料单', `${JM_WORKORDERID}🈹`);
          if (lldInfoList.filter(p => p.STATE == 1).length > 0) {
            throw new Error("物料配送单已生成，不能删除");
          }
          //#endregion

          //#region 检查TASKCARD
          // 根据订单查找订单下SN
          let snParam = `JM_WORKORDERSN🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
          let snInfoList = await myAxios.get('陈帅廷查询大连通用数据', snParam);
          for (let i = 0; i < snInfoList.length; i++) {
            let snInfo = snInfoList[i];
            let tkParam = `TASKCARD🈹PROSN🈹${snInfo['PROSN']}`;
            let tkInfoList = await myAxios.get('陈帅廷查询大连通用数据', tkParam);
            let length = tkInfoList.length;
            if (length > 0) {
              throw new Error("SN[" + snInfo['PROSN'] + "]已经生成任务卡片，不能删除");
            }
          }
          //#endregion

          //#region 删除JM_WORKORDERSNRECORD
          let jpParam = `JM_JOBPLAN🈹WONO🈹${JM_WORKORDERID}`;
          let jpInfoList = await myAxios.get('陈帅廷查询大连通用数据', jpParam);
          for (let i = 0; i < jpInfoList.length; i++) {
            let jpInfo = jpInfoList[i];
            let recordParam = `JM_WORKORDERSNRECORD🈹PLANID🈹${jpInfo.JM_JOBPLANID}`;
            let recordInfoList = await myAxios.get('陈帅廷查询大连通用数据', recordParam);
            for (let j = 0; j < recordInfoList.length; j++) {
              let recordInfo = recordInfoList[j];
              let deleteParam = `JM_WORKORDERSNRECORD🈹JM_WORKORDERSNRECORDID🈹${recordInfo.JM_WORKORDERSNRECORDID}`;
              let deleteResult = await myAxios.post(`陈帅廷删除大连通用数据`, deleteParam);
            }
          }
          //#endregion

          //#region 删除调度
          for (let i = 0; i < ddInfoList.length; i++) {
            let JM_JOBBATCHNOID = ddInfoList['JM_JOBBATCHNOID'];
            let deleteParam = `JM_JOBBATCHNO🈹JM_JOBBATCHNOID🈹${JM_JOBBATCHNOID}`;
            let deleteResult = await myAxios.post(`陈帅廷删除大连通用数据`, deleteParam);
          }
          //#endregion

          //#region 删除计划
          for (let i = 0; i < jpInfoList.length; i++) {
            let jpInfo = jpInfoList[i];
            let deleteParam = `JM_JOBPLAN🈹JM_JOBPLANID🈹${jpInfo.JM_JOBPLANID}`;
            let deleteResult = await myAxios.post(`陈帅廷删除大连通用数据`, deleteParam);
          }
          //#endregion

          //#region 删除订单

          let deleteOrderParam = `JM_WORKORDER🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
          let deleteOrderResult = await myAxios.post(`陈帅廷删除大连通用数据`, deleteOrderParam);
          //#endregion



          resolve(`订单 ${JM_WORKORDERID} 下达检查成功,可以下达`);
        }
        catch (err) {
          resolve(`订单 ${JM_WORKORDERID} ` + err.message);
        }
      });
    };
    //#endregion

    //#region 插入函数

    let insert_JM_WORKORDERSNRECORD = async function (snList, routeList) {
      return new Promise(async (resolve, reject) => {
        let result = [];

        // 处理每个流水号
        for (let i = 0; i < snList.length; i++) {
          const item = snList[i];
          let lastRecordId = "";

          // 处理每条工艺路线
          for (let j = 0; j < routeList.length; j++) {
            let routeItem = routeList[j];
            if (routeItem.WOROUTE === 'F0010') {
              continue;
            }
            const newId = v4();
            const usdState = lastRecordId ? 0 : 4;

            // 插入新记录
            let snRecordParam = `${newId}🈹${item.PROSN}🈹${routeItem.WOROUTE}`
              + `🈹${routeItem.ROUTENO}🈹${usdState}🈹${routeItem.JM_WORKORDERID}`
              + `🈹${lastRecordId || ""}`;
            let snRecordResult = await myAxios.post('陈帅廷插入大连订单SNRECORD', snRecordParam, '9900');
            result.push('陈帅廷插入大连订单SNRECORD :>> ' + newId + ' :>> ' + snRecordResult);
            lastRecordId = newId;
          }
        }

        resolve(result);
      });
    };

    let insert_MATERIALAPPLYFORSN = async function (row, bomList, appList, routeList, snList) {
      return new Promise(async (resolve, reject) => {

        // 处理每个BOM项
        let result = [];
        for (let i = 0; i < bomList.length; i++) {
          const item = bomList[i];

          if (item.MATCODE.startsWith("ZJ")) {
            continue;
          }

          const txt = item.DATA3 || "";

          if (txt.length > 0) {
            const sns0 = txt.split(',');
            for (let j = 0; j < sns0.length; j++) {
              const sn = sns0[j];
              const sn2 = row.MATCODE + sn;

              // 检查是否已存在领料记录
              let existing = appList.filter(app =>
                app.SN == sn2
                && app.ORDERNO == row.JM_WORKORDERID
                && app.MATERIALID == item.MATCODE);

              if (existing.length === 0) {
                // 查询工艺路线
                // let routeParam = `JM_ORDERROUTE🈹JM_ORDERROUTEID🈹${item.WOROUTE}`;
                // let routeInfo = await myAxios.get('陈帅廷查询大连通用数据', routeParam);
                let routeInfo = routeList.filter(el => el.JM_ORDERROUTEID === item.WOROUTE);
                let workingId = routeInfo[0]?.WOROUTE;

                // 准备插入数据
                const MATERIALAPPLYFORSN_FIELDS = [
                  'SNAPPLYID', 'ORDERNO', 'ORDERMATCODE', 'SN',
                  'MATERIALID', 'QTY', 'STATE', 'CREATETIME',
                  'DataVersion', 'WORKINGID',
                ];
                let insertData = {
                  SNAPPLYID: v4(),
                  ORDERNO: row.JM_WORKORDERID,
                  ORDERMATCODE: row.MATCODE,
                  SN: sn2,
                  MATERIALID: item.MATCODE,
                  QTY: item.BOMDOSAGE,
                  STATE: "0",
                  CREATETIME: dayjs().format("YYYY/MM/DD HH:mm:ss"),
                  DataVersion: 1,
                  WORKINGID: workingId
                };

                // 插入新记录
                let orderedValues = MATERIALAPPLYFORSN_FIELDS.map(field => insertData[field]);
                let insertParam = `${orderedValues.join('🈹')}`;
                let result_MATERIALAPPLYFORSN = await myAxios.post('陈帅廷插入大连订单MATERIALAPPLYFORSN', insertParam);
                result.push('陈帅廷插入大连订单MATERIALAPPLYFORSN :>> ' + insertData[`SNAPPLYID`] + ' 1:>> ' + result_MATERIALAPPLYFORSN);
              }
            }
          } else {
            for (let k = 0; k < snList.length; k++) {
              const sn = snList[k];

              // 检查是否已存在领料记录
              // 检查是否已存在记录
              // let checkParam = `MATERIALAPPLYFORSN🈹SN,ORDERNO,MATERIALID🈹${sn.PROSN},${row.JM_WORKORDERID},${item.MATCODE}`;
              // let existing = await myAxios.get('陈帅廷查询大连通用数据', checkParam);
              let existing = appList.filter(app =>
                app.SN == sn.PROSN
                && app.ORDERNO == row.JM_WORKORDERID
                && app.MATERIALID == item.MATCODE);

              if (existing.length === 0) {
                // 查询工艺路线
                // let routeParam = `JM_ORDERROUTE🈹JM_ORDERROUTEID🈹${item.WOROUTE}`;
                // let routeInfo = await myAxios.get('陈帅廷查询大连通用数据', routeParam);
                let routeInfo = routeList.filter(el => el.JM_ORDERROUTEID === item.WOROUTE);
                let workingId = routeInfo[0]?.WOROUTE;

                // 计算数量
                let qty = (k === snList.length - 1) ?
                  (item.BOMAMOUNT - item.BOMDOSAGE * k) :
                  item.BOMDOSAGE;


                // 准备插入数据
                const MATERIALAPPLYFORSN_FIELDS = [
                  'SNAPPLYID', 'ORDERNO', 'ORDERMATCODE', 'SN',
                  'MATERIALID', 'QTY', 'STATE', 'CREATETIME',
                  'DataVersion', 'WORKINGID',
                ];
                let insertData = {
                  SNAPPLYID: v4(),
                  ORDERNO: row.JM_WORKORDERID,
                  ORDERMATCODE: row.MATCODE,
                  SN: sn.PROSN,
                  MATERIALID: item.MATCODE,
                  QTY: qty,
                  STATE: "0",
                  CREATETIME: dayjs().format("YYYY/MM/DD HH:mm:ss"),
                  DataVersion: 1,
                  WORKINGID: workingId
                };

                // 插入新记录
                let orderedValues = MATERIALAPPLYFORSN_FIELDS.map(field => insertData[field]);
                let insertParam = `${orderedValues.join('🈹')}`;
                let result_MATERIALAPPLYFORSN = await myAxios.post('陈帅廷插入大连订单MATERIALAPPLYFORSN', insertParam);
                result.push('陈帅廷插入大连订单MATERIALAPPLYFORSN :>> ' + insertData[`SNAPPLYID`] + ' 2:>> ' + result_MATERIALAPPLYFORSN);
              }
            }
          }
        }

        resolve(result);
      });
    };

    //#endregion

    //#region 删除函数

    let delete_JM_WORKORDERSNRECORD = async function (JM_WORKORDERID) {
      return new Promise(async (resolve, reject) => {
        let result = [];

        // 处理每个流水号
        for (let i = 0; i < snList.length; i++) {
          const item = snList[i];
          let lastRecordId = "";

          // 处理每条工艺路线
          for (let j = 0; j < routeList.length; j++) {
            let routeItem = routeList[j];
            if (routeItem.WOROUTE === 'F0010') {
              continue;
            }
            const newId = v4();
            const usdState = lastRecordId ? 0 : 4;

            // 插入新记录
            let snRecordParam = `${newId}🈹${item.PROSN}🈹${routeItem.WOROUTE}`
              + `🈹${routeItem.ROUTENO}🈹${usdState}🈹${routeItem.JM_WORKORDERID}`
              + `🈹${lastRecordId || ""}`;
            let snRecordResult = await myAxios.post('陈帅廷插入大连订单SNRECORD', snRecordParam, '9900');
            result.push('陈帅廷插入大连订单SNRECORD :>> ' + newId + ' :>> ' + snRecordResult);
            lastRecordId = newId;
          }
        }

        resolve(result);
      });
    };

    let delete_MATERIALAPPLYFORSN = async function (JM_WORKORDERID) {
      return new Promise(async (resolve, reject) => {

        // 处理每个BOM项
        let result = [];
        for (let i = 0; i < bomList.length; i++) {
          const item = bomList[i];

          if (item.MATCODE.startsWith("ZJ")) {
            continue;
          }

          const txt = item.DATA3 || "";

          if (txt.length > 0) {
            const sns0 = txt.split(',');
            for (let j = 0; j < sns0.length; j++) {
              const sn = sns0[j];
              const sn2 = row.MATCODE + sn;

              // 检查是否已存在领料记录
              let existing = appList.filter(app =>
                app.SN == sn2
                && app.ORDERNO == row.JM_WORKORDERID
                && app.MATERIALID == item.MATCODE);

              if (existing.length === 0) {
                // 查询工艺路线
                // let routeParam = `JM_ORDERROUTE🈹JM_ORDERROUTEID🈹${item.WOROUTE}`;
                // let routeInfo = await myAxios.get('陈帅廷查询大连通用数据', routeParam);
                let routeInfo = routeList.filter(el => el.JM_ORDERROUTEID === item.WOROUTE);
                let workingId = routeInfo[0]?.WOROUTE;

                // 准备插入数据
                const MATERIALAPPLYFORSN_FIELDS = [
                  'SNAPPLYID', 'ORDERNO', 'ORDERMATCODE', 'SN',
                  'MATERIALID', 'QTY', 'STATE', 'CREATETIME',
                  'DataVersion', 'WORKINGID',
                ];
                let insertData = {
                  SNAPPLYID: v4(),
                  ORDERNO: row.JM_WORKORDERID,
                  ORDERMATCODE: row.MATCODE,
                  SN: sn2,
                  MATERIALID: item.MATCODE,
                  QTY: item.BOMDOSAGE,
                  STATE: "0",
                  CREATETIME: dayjs().format("YYYY/MM/DD HH:mm:ss"),
                  DataVersion: 1,
                  WORKINGID: workingId
                };

                // 插入新记录
                let orderedValues = MATERIALAPPLYFORSN_FIELDS.map(field => insertData[field]);
                let insertParam = `${orderedValues.join('🈹')}`;
                let result_MATERIALAPPLYFORSN = await myAxios.post('陈帅廷插入大连订单MATERIALAPPLYFORSN', insertParam);
                result.push('陈帅廷插入大连订单MATERIALAPPLYFORSN :>> ' + insertData[`SNAPPLYID`] + ' 1:>> ' + result_MATERIALAPPLYFORSN);
              }
            }
          } else {
            for (let k = 0; k < snList.length; k++) {
              const sn = snList[k];

              // 检查是否已存在领料记录
              // 检查是否已存在记录
              // let checkParam = `MATERIALAPPLYFORSN🈹SN,ORDERNO,MATERIALID🈹${sn.PROSN},${row.JM_WORKORDERID},${item.MATCODE}`;
              // let existing = await myAxios.get('陈帅廷查询大连通用数据', checkParam);
              let existing = appList.filter(app =>
                app.SN == sn.PROSN
                && app.ORDERNO == row.JM_WORKORDERID
                && app.MATERIALID == item.MATCODE);

              if (existing.length === 0) {
                // 查询工艺路线
                // let routeParam = `JM_ORDERROUTE🈹JM_ORDERROUTEID🈹${item.WOROUTE}`;
                // let routeInfo = await myAxios.get('陈帅廷查询大连通用数据', routeParam);
                let routeInfo = routeList.filter(el => el.JM_ORDERROUTEID === item.WOROUTE);
                let workingId = routeInfo[0]?.WOROUTE;

                // 计算数量
                let qty = (k === snList.length - 1) ?
                  (item.BOMAMOUNT - item.BOMDOSAGE * k) :
                  item.BOMDOSAGE;


                // 准备插入数据
                const MATERIALAPPLYFORSN_FIELDS = [
                  'SNAPPLYID', 'ORDERNO', 'ORDERMATCODE', 'SN',
                  'MATERIALID', 'QTY', 'STATE', 'CREATETIME',
                  'DataVersion', 'WORKINGID',
                ];
                let insertData = {
                  SNAPPLYID: v4(),
                  ORDERNO: row.JM_WORKORDERID,
                  ORDERMATCODE: row.MATCODE,
                  SN: sn.PROSN,
                  MATERIALID: item.MATCODE,
                  QTY: qty,
                  STATE: "0",
                  CREATETIME: dayjs().format("YYYY/MM/DD HH:mm:ss"),
                  DataVersion: 1,
                  WORKINGID: workingId
                };

                // 插入新记录
                let orderedValues = MATERIALAPPLYFORSN_FIELDS.map(field => insertData[field]);
                let insertParam = `${orderedValues.join('🈹')}`;
                let result_MATERIALAPPLYFORSN = await myAxios.post('陈帅廷插入大连订单MATERIALAPPLYFORSN', insertParam);
                result.push('陈帅廷插入大连订单MATERIALAPPLYFORSN :>> ' + insertData[`SNAPPLYID`] + ' 2:>> ' + result_MATERIALAPPLYFORSN);
              }
            }
          }
        }

        resolve(result);
      });
    };

    //#endregion

    let buttonClicks = {
      addBtnClick: addBtnClick,
      inputBtnClick: inputBtnClick,
      xiaDaBtnClick: xiaDaBtnClick,
      quXiaoXiaDaBtnClick: quXiaoXiaDaBtnClick,
      deleteBtnClick: deleteBtnClick,
      refreshBtnClick: refreshBtnClick,
      finishBtnClick: finishBtnClick,
    };

    let showFormDialog = function (data) {
      dialogDatas.title = '订单号: ' + data.orderId;
      dialogDatas.orderData = data;
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      title: '',
      orderData: {
        workorder: {},
        processData: {
          tableData: [],
          handleAdd: function () {
            console.log('1 :>> ', 1);
          },
          handleDelete: function () {
            console.log('2 :>> ', 2);
          },
          handleReplace: function () {
            console.log('3 :>> ', 3);
          },
        },
      },
      dialogFormVisible: false,
      confirmBtnClick: function () {
      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = function () {
      loading.value = true;
      let params = `${tableDatas.filters.state}`;
      // let name = `陈帅廷查询大连订单信息(测试)`;
      let name = `陈帅廷查询大连订单信息`;
      if (tableDatas.filters.state == 10) {
        params = `<>`;
        name = `陈帅廷查询大连排产中订单`;
      }
      else if (tableDatas.filters.state == 11) {
        params = `=`;
        name = `陈帅廷查询大连排产中订单`;
      }
      myAxios.get(name, params, '9900').then(res => {
        if (res instanceof Array) {
          loading.value = false;
          res.forEach(item => {
            item.checked = false;
          });
          tableDatas.oritableData = [...res];
          let time = dayjs().format('YYYY/MM/DD HH:mm:ss');
          showSuccess(time + ' 最新数据获取成功!');
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      getTableDatas();
    });

    let searchKeys = ['JM_WORKORDERID', 'MATCODE', 'MATNAME'];
    let dropdown = ref(null);
    let tableDatas = reactive({
      virtualTableColumns: [
        {
          key: 'index',
          title: '序号',
          width: 60,
          align: 'center',
          cellRenderer: ({ rowIndex }) => rowIndex + 1
        },
        {
          key: 'checked',
          dataKey: 'checked',
          title: '选择',
          width: 60,
          align: 'center',
        },
        {
          key: 'JM_WORKORDERID',
          dataKey: 'JM_WORKORDERID',
          title: '订单号',
          width: 140,
          align: 'center',
        },
        {
          key: 'MATCODE',
          title: '物料号',
          width: 100,
          align: 'center',
        },
        {
          key: 'MATNAME',
          title: '物料描述',
          width: 200,
          align: 'center',
        },
        {
          key: 'WOPLANDATE',
          title: '计划开始日期',
          width: 110,
          align: 'center',
        },
        {
          key: 'WOCOMDATE',
          title: '计划完成日期',
          width: 110,
          align: 'center',
        },
        {
          key: 'WOPLANQTY',
          title: '计划数量',
          width: 90,
          align: 'center',
        },
        {
          key: 'WOSCHEDULEQTY',
          title: '排产数量',
          width: 90,
          align: 'center',
        },
        {
          key: 'WOCOMPQTY',
          title: '完成数量',
          width: 90,
          align: 'center',
        },
        {
          key: 'WOCOMMENTS',
          title: '备注',
          width: 500,
          align: 'center',
        },
        {
          key: 'CREATETIME',
          title: '创建日期',
          width: 100,
          align: 'center',
        },
      ],
      //表格筛选展示相关代码
      filters: {
        state: 0,
        stateOptions: [
          { value: 0, label: '新建' },
          { value: 10, label: '开始' },
          // { value: 11, label: '排产完' },
          { value: 3, label: '完工' },
          { value: 2, label: '暂停或关闭' },
        ],
        searchText: '',
        dateRange: [],

        contextMenu: {
          visible: false,
          left: 0,
          top: 0,
          row: null,
          index: -1,
        },

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;

        if (tableDatas.filters.searchText) {
          let searchText = tableDatas.filters.searchText;
          fData = fData.filter(item => {
            return searchKeys.some(key => {
              return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
            });
          });
        }

        if (tableDatas.filters.dateRange && tableDatas.filters.dateRange.length) {
          fData = fData.filter(item => {
            console.log('item.WOPLANDATE :>> ', item.WOPLANDATE);
            let WOPLANDATE = item.WOPLANDATE.substring(0, 10);
            return WOPLANDATE >= tableDatas.filters.dateRange[0] && WOPLANDATE <= tableDatas.filters.dateRange[1];
          });
        }

        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        console.log('fData :>> ', fData);
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        {
          "type": "index",
          "prop": "",
          "label": "序号",
          "align": "center",
          "width": 60
        },
        {
          "prop": "checked",
          "label": "选择",
          "align": "center",
          "width": 60,
        },
        {
          "prop": "JM_WORKORDERID",
          "label": "订单号",
          "align": "center",
          "width": 100,

        },
        {
          "prop": "MATCODE",
          "label": "物料号",
          "align": "center",
          "width": 100,
        },
        {
          "prop": "MATNAME",
          "label": "物料描述",
          "align": "center",
          "width": 200,
        },
        {
          "prop": "WOPLANDATE",
          "label": "计划开始日期",
          "align": "center",
          "width": 110,
          "formatter": function (row, column) {
            try {
              return row['CREATETIME'].substring(0, 10);
            }
            catch (e) {
              return row['CREATETIME'];
            }
          },
        },
        {
          "prop": "WOCOMDATE",
          "label": "计划完成日期",
          "align": "center",
          "width": 110,
          "formatter": function (row, column) {
            try {
              return row['CREATETIME'].substring(0, 10);
            }
            catch (e) {
              return row['CREATETIME'];
            }
          },
        },
        {
          "prop": "WOPLANQTY",
          "label": "计划数量",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "WOSCHEDULEQTY",
          "label": "排产数量",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "WOCOMPQTY",
          "label": "完成数量",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "WOCOMMENTS",
          "label": "备注",
          "align": "center",
        },
        {
          "prop": "CREATETIME",
          "label": "创建日期",
          "align": "center",
          "width": 100,
          "formatter": function (row, column) {
            try {
              return row['CREATETIME'].substring(0, 10);
            }
            catch (e) {
              return row['CREATETIME'];
            }
          },
        },
        // {
        //   "prop": "operate",
        //   "label": "操作",
        //   "align": "center",
        //   "width": 170,
        // },
      ],
      oritableData: [
      ],
      handleVirtualContextMenu: function ({ rowData: row, event }) {
        event.preventDefault();
        tableDatas.filters.contextMenu.visible = false;
        // const tableRect = event.currentTarget.getBoundingClientRect();

        nextTick(() => {
          dropdown.value.handleClose();
        });
        // tableDatas.filters.contextMenu = {
        //   visible: true,
        //   left: event.clientX - tableRect.left,
        //   top: event.clientY - tableRect.top,
        //   row: row,
        //   index: tableDatas.oritableData.indexOf(row)
        // };

        tableDatas.filters.contextMenu = {
          visible: true,
          left: event.clientX,
          top: event.clientY,
          row: row,
          index: tableDatas.oritableData.indexOf(row),
        };

        setTimeout(() => {
          dropdown.value.handleOpen();
        }, 1);
        // 手动触发dropdown显示
      },
      handleContextMenu: function (row, column, event) {
        event.preventDefault();
        tableDatas.filters.contextMenu.visible = false;
        // const tableRect = event.currentTarget.getBoundingClientRect();

        nextTick(() => {
          dropdown.value.handleClose();
        });
        // tableDatas.filters.contextMenu = {
        //   visible: true,
        //   left: event.clientX - tableRect.left,
        //   top: event.clientY - tableRect.top,
        //   row: row,
        //   index: tableDatas.oritableData.indexOf(row)
        // };

        tableDatas.filters.contextMenu = {
          visible: true,
          left: event.clientX,
          top: event.clientY,
          row: row,
          index: tableDatas.oritableData.indexOf(row),
        };

        setTimeout(() => {
          dropdown.value.handleOpen();
        }, 1);
        // 手动触发dropdown显示
      },
      handleMenuClick: async function (action) {
        loading.value = true;
        tableDatas.filters.contextMenu.visible = false;

        let orderId = tableDatas.filters.contextMenu.row.JM_WORKORDERID;
        let orderData = {
          orderId: orderId,
          workorder: tableDatas.filters.contextMenu.row,
          processData: {
            tableData: [],
          },
          bomData: {
            tableData: [],
          },
          snData: {
            tableData: [],
          }
        };
        let processParam = `${orderId}`;
        let processData = await myAxios.get('陈帅廷查询大连订单工艺路线', processParam);
        orderData.processData.tableData = processData;

        let bomParam = `${orderId}`;
        let bomData = await myAxios.get('陈帅廷查询大连订单BOM', bomParam);
        orderData.bomData.tableData = bomData;

        let snParam = `${orderId}`;
        let snData = await myAxios.get('陈帅廷查询大连订单SN使用状态', snParam);
        orderData.snData.tableData = snData;

        console.log(orderData);
        // 根据action执行不同操作
        switch (action) {
          case '查看详情':
            showFormDialog(orderData);
            break;
          case 'delete':
            // 删除逻辑
            tableDatas.oritableData.splice(tableDatas.filters.contextMenu.index, 1);
            break;
          case 'copy':
            // 复制逻辑
            break;
        }
        loading.value = false;
      },
      tableRowClassName: function ({ rowData, rowIndex, }) {
        if (rowData.checked) {
          return 'success-row';
        }
        return rowIndex % 2 === 1 ? 'striped-row' : '';
      },
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;
        let JM_WORKORDERID = row.JM_WORKORDERID;

        let params = `0004`;
        myAxios.post('删除', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            showSuccess('删除成功!' + res);
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
    });

    return {
      loading,
      buttonClicks,
      getTableDatas,
      dialogDatas,
      // 表格菜单
      dropdown,
      tableDatas
    };
  }
}
</script>
<style scoped>
.marginTop10 {
  margin-top: 10px;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
:deep(.success-row) {
  background-color: var(--el-color-success-light-7);
}

:deep(.striped-row) {
  background-color: #f5f7fa;
}

/* 边框样式 */
:deep(.bordered-table) {
  border: 1px solid #ebeef5;
}

:deep(.bordered-table .el-table-v2__header-cell) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.bordered-table .el-table-v2__row-cell) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
</style>

